package demo;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description: 两个队列实现栈 力扣225题
 * User: 86187
 * Date: 2022-07-30
 * Time: 18:10
 */

class MyStack {
    Queue<Integer> qu1;
    Queue<Integer> qu2;
    public int usedSize;

    //构造方法
    public MyStack() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }

    //用队列实现入栈
    public void push(int x) {
        if(!qu1.isEmpty()) {
            qu1.offer(x); //入队
        }else if(!qu2.isEmpty()) {
            qu2.offer(x);
        }else {
            qu1.offer(x);
        }
        usedSize++;
    }

    //用队列实现出栈
    public int pop() {
        if(empty()) {
            //栈为空返回-1
            return -1;
        }
        if(!qu1.isEmpty()) {
            //qu1.size()的值会随着出队而变化，所以要记录，下同
            int curSize = qu1.size();
            for (int i = 0; i < curSize-1; i++) {
                qu2.offer(qu1.poll());
            }
            return qu1.poll();
        }else {
            int curSize = qu2.size();
            for (int i = 0; i < curSize-1; i++) {
                qu1.offer(qu2.poll());
            }
            return qu2.poll();
        }
    }

    //获取栈顶元素
    public int top() {
        if(empty()) {
            //栈为空返回-1
            return -1;
        }
        if(!qu1.isEmpty()) {
            //qu1.size()的值会随着出队而变化，所以要记录，下同
            int curSize = qu1.size();
            int curNumber = -1;
            for (int i = 0; i < curSize; i++) {
                curNumber = qu1.poll();
                qu2.offer(curNumber);
            }
            return curNumber;
        }else {
            int curSize = qu2.size();
            int curNumber = -1;
            for (int i = 0; i < curSize; i++) {
                curNumber = qu2.poll();
                qu1.offer(curNumber);
            }
            return curNumber;
        }
    }

    //判空
    public boolean empty() {
        return usedSize == 0;
    }
}
